"use strict";

import config from "./Config";

import testFeedStr from "../../tests/feed";
const request = Rokid.request;
// const request = require('request');

/**
 * @class RSS RSS辅助
 */
class RSS {
  /**
   * @method constructor
   */
  constructor() {
    this._error = null;
    this._source = "cos";
    this._cache_type = "none";
    this._error = null;

    this._config = {
      mode: "simple" // simple | full
    };

    this._rss = null;
    this._level = "title";
    this._channel = "优惠精选";
    this._channels = [
      {
        name: "feed",
        tags: ["优惠精选"],
        url: "http://feed.smzdm.com/"
      },
      {
        name: "haitao",
        tags: ["海淘专区"],
        url: "http://haitao.smzdm.com/feed"
      },
      {
        name: "post",
        tags: ["原创频道"],
        url: "http://post.smzdm.com/feed"
      },
      {
        name: "faxian",
        tags: ["发现频道"],
        url: "http://faxian.smzdm.com/feed"
      },
      {
        name: "news",
        tags: ["资讯专区"],
        url: "http://news.smzdm.com/feed"
      }
    ];
    this._items = [];

    switch (this._cache_type) {
      case "memory":
        cache = cacheMemory;
        break;
      case "file":
        cache = cacheFile;
        break;
      default:
        break;
    }
  }

  setConfig(config) {
    if (config.hasOwnProperty("mode")) {
      if (["全文"].contains(config.mode)) {
        this._config.mode = "full";
      } else {
        this._config.mode = "simple";
      }
    }
  }

  getChannelAttr(rss, field = "url") {
    let self = this;
    let res = "";
    self._channels.forEach(item => {
      if (item.name === rss || item.tags.contains(rss)) {
        if (field === "cos_title") {
          res =
            "http://spider-1251008422.cossh.myqcloud.com/smzdm/rss/" +
            item.name +
            "_title.json";
        } else if (field === "cos_item") {
          res =
            "http://spider-1251008422.cossh.myqcloud.com/smzdm/rss/" +
            item.name +
            "_item.json";
        } else {
          res = item[field];
        }
      }
    });
    return res;
  }

  setChannel(channel) {
    let self = this;
    if (self.getChannelAttr(channel)) {
      // console.debug('[SET CHANNEL]', self.getChannelAttr(channel), channel)
      self._channel = channel;
    }
  }

  getPageNo(page, offset, direction) {
    if (["前", "上"].contains(direction)) {
      page -= offset;
    } else {
      page += offset;
    }
    return page;
  }

  pager(page = 1, size = 5) {
    let self = this;
    if (self._error) {
      return self._error;
    } else {
      let pages = 1;
      let items = [];
      let offset = (page - 1) * size;
      if (self._items && self._items.length > 0) {
        pages = Math.ceil(self._items.length / size);
      }
      if (page > pages) page = pages;
      self._items.forEach((item, index) => {
        if (index >= offset && index < page * size) {
          // items.push(item.title);
          switch (self._level) {
            case "title":
              let titleSplit = item.title.split("：");
              if (titleSplit.length > 1) {
                item.title = titleSplit.slice(1).join("：");
              }
              items.push(item);
              break;
            default:
              items.push(item);
              break;
          }
        }
      });
      return {
        page,
        pages,
        size,
        items
      };
    }
  }

  ssml(items) {
    let ttsStr = items.map(item => {
      return "<p>" + item.title + "</p>";
    });

    return "<speak>" + ttsStr.join("") + "</speak>";
  }

  fetchOnline(rss) {
    let result = [];
    let self = this;
    return new Promise((resolve, reject) => {
      request(
        {
          method: "GET",
          url: self.getChannelAttr(rss, "cos_" + self._level),
          headers: {
            "User-Agent": "request"
          }
        },
        function(error, response, body) {
          if (error) {
            console.debug("[FETCH ONLINE ERROR]", error);
            self._error = "请求网络错误，请稍后重试。";
          }
          resolve(JSON.parse(body));
        }
      );
    });
  }

  fetch(channel) {
    let self = this;
    if (!channel) channel = self._channel;
    return self.fetchOnline(channel, self._level).then(result => {
      return new Promise((resolve, reject) => {
        if (result.hasOwnProperty("items") && result.items.length > 0) {
          self._items = result.items;
        }
        resolve(self._items);
      });
    });
  }
}

export default RSS;
